package com.chinatsp.onlineapp.ui.main_menu;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import tsp.cn.http.interfac.IProtolResult;
import tsp.cn.http.tools.PreferenceUtils;
import tsp.cn.http.tools.LogUtil;
import tsp.cn.http.tools.T;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.util.Log;
import android.util.TimeUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chinatsp.onlineapp.App;
import com.chinatsp.onlineapp.R;
import com.chinatsp.onlineapp.base.BaseActivity;
import com.chinatsp.onlineapp.base.BaseApplication;
import com.chinatsp.onlineapp.base.Config;
import com.chinatsp.onlineapp.base.Constant;
import com.chinatsp.onlineapp.bean.LimitNum;
import com.chinatsp.onlineapp.bean.ReverseGeocod;
import com.chinatsp.onlineapp.bean.WeatherService.RespDataBean.CurrentConditionsBean;
import com.chinatsp.onlineapp.bean.WeatherService.RespDataBean.ForecastConditionsBean;
import com.chinatsp.onlineapp.presenter.GetAllCityDao;
import com.chinatsp.onlineapp.presenter.GetHotCityDao;
import com.chinatsp.onlineapp.presenter.LimitNumDao;
import com.chinatsp.onlineapp.presenter.NewsListDao;
import com.chinatsp.onlineapp.presenter.ReverseGeocodeDao;
import com.chinatsp.onlineapp.presenter.WeatherServiceDao;
import com.chinatsp.onlineapp.protocol.ProtocalTools;
import com.chinatsp.onlineapp.service.LocationService;
import com.chinatsp.onlineapp.service.NetWeatherService;
import com.chinatsp.onlineapp.ui.limit_rule.LimitNumActivity;
import com.chinatsp.onlineapp.ui.news.NewsMainActivity;
import com.chinatsp.onlineapp.ui.violation.QueryViolationActivity;
import com.chinatsp.onlineapp.ui.weather.WeatherSinglePageActivity;
import com.chinatsp.onlineapp.utils.ActivityUtil;
import com.chinatsp.onlineapp.utils.DateUtil;
import com.chinatsp.onlineapp.utils.TimeTool;
import com.chinatsp.onlineapp.utils.WeatherType;

public class MainActivity extends BaseActivity implements View.OnClickListener,IProtolResult {

	private RelativeLayout rlQueryViolation;
	private RelativeLayout rlTodayLimit;
	private RelativeLayout rlNews;
	private ViewGroup llWeather;
	private ListView lv;
	private ImageView ivBack;
	private ImageView ivWeatherShow;
	private TextView tvPosition;
	private TextView  tvToday;
	private WeatherListAdapter adapter;
	private List<ForecastConditionsBean> forecastConditions;
	private WeatherServiceDao mWeatherServiceDao;
	private NewsListDao mNewsListDao;
	private LimitNumDao mLimitNumDao;
    private ReverseGeocodeDao mReverseGeocodeDao;
    GetAllCityDao mGetAllCityDao;
    GetHotCityDao mGetHotCityDao;
    
	private TextView tv_limit_number;
	 
	private String mDefaultCity = "";  
	@Override
	public void onRequestSuccess(int requestCode) { 
		super.onRequestSuccess(requestCode);
		showProgress(false);
		// 开始更新UI

		switch (requestCode) {
		case Config.CODE_WEATHER_SERVICE:// 更新天气数据
			LogUtil.d( "update CODE_WEATHER_SERVICE");
			CurrentConditionsBean current_conditions = mWeatherServiceDao.getmWeatherService().getResp_data().getCurrent_conditions();
			//forecastConditions = mWeatherServiceDao.getmWeatherService().getResp_data().getForecast_conditions();
			adapter.setData(mWeatherServiceDao.getmWeatherService().getResp_data().getForecast_conditions());
			//adapter.notifyDataSetChanged();
			Log.e("----mainweather", current_conditions.getAirpollution_index());
			
			String str_position = mWeatherServiceDao.getmWeatherService().getResp_data().getCity_name();			 
			 String str_time = mWeatherServiceDao.getmWeatherService().getResp_data().getRelease_time().replace("/", "-");
			 Date release_date = DateUtil.changeStringToDate(str_time);
			 
			 String str_week = DateUtil.getWeek(release_date);
			 String str_temperature =current_conditions.getLow_temperature()+" - "+current_conditions.getHigh_temperature();
			 String str_weather = current_conditions.getWeather_condition();
			 String str_prompt = current_conditions.getDress_index();
			 String str_date  = (release_date.getMonth()+1)+"."+release_date.getDate();
			 tv_mweek.setText(str_date+" "+str_week);
			 tv_temperature.setText(str_temperature);
			 tv_state.setText(str_weather);
			 tv_prompt.setText(str_prompt);
			 tv_limit_position.setText(str_position); 
			 tvToday.setVisibility(View.VISIBLE);
			 ivWeatherShow.setVisibility(View.VISIBLE);
			 
			 String type = current_conditions.getWeather_type();
			 WeatherType.showImg(type, ivWeatherShow);
			
			break;
		case Config.CODE_NEWS_LIST:// 更新新闻数据
			LogUtil.d( "update CODE_NEWS_LIST");
			break;
		case Config.CODE_LIMIT_NUM:// 更新限号数据
			
			LogUtil.d( "update CODE_LIMIT_NUM");
			
			// 更新界面数据
			LimitNum limitNum = mLimitNumDao.getLimitNum();
			tv_limit_number.setText(limitNum.getResp_data().getLimit_code());
			
			

			break;
		case Config.CODE_REVERS_GEOCODE:// 定位根据经纬度获取城市		
			
			// 更新界面数据
			ReverseGeocod reverseGeocod = mReverseGeocodeDao.getReverseGeocod();
			LogUtil.d("cityName" + reverseGeocod.getResp_data().getCity_name());
			String city = reverseGeocod.getResp_data().getCity_name();
			LogUtil.d( "location current "+city);
			tvPosition.setText(city);
			if(!city.equals(mDefaultCity)){			
				PreferenceUtils.savePreference("default_city", mDefaultCity);
				testLimitAndWeather();
				LogUtil.d( "city update");
			}else{
				LogUtil.d( "city same");
			}
			
			break;
		case Config.CODE_GET_ALL_CITY:{
			
				String current_date = TimeTool.getCurrentDates();
				//PreferenceUtils.savePreference("all_city_latest", current_date);
				mGetAllCityDao.getAllCityBean().getResp_status();
			}
			break;
		case Config.CODE_GET_HOT_CITY:
			{
				String current_date = TimeTool.getCurrentDates();
				//PreferenceUtils.savePreference("hot_city_latest", current_date);
				mGetHotCityDao.getHotCityBean().getResp_status();
			}	
			break;
		}
	}
	
	private void testLimitAndWeather(){
		
		// 获取天气
		//mWeatherServiceDao.getmWeatherService();
		
		// 今日限号
		//mLimitNumDao.getLimitNum();
		// 获取天气数据
		String default_city = getDeafaultCity();
		if(default_city!=null){
			mWeatherServiceDao.getWeatherService(default_city);
			// 获取限号数据
			mLimitNumDao.getLimitNum(default_city);
		}
//		mNewsListDao.getNewsList();
		
	}

	@Override
	public void onRequestFailed(String errorNo, String errorMessage) {
		super.onRequestFailed(errorNo, errorMessage);
		
     	LogUtil.d( "MainActivity onRequestFailed");
     	

	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		initView();
		showProgress(true);
		initProtocol();
		
		getDeafaultCity();
		startLacation();
		
	}
	
	void initProtocol(){
		ProtocalTools protocalTools = new ProtocalTools(this);
		protocalTools.startCommunicate();
		if(protocalTools.isActiveSuccess()){
			initDao();
		}else{
			protocalTools.setIProtolResult(this);
		}
	}
	
	String getDeafaultCity(){
		String default_city = PreferenceUtils.getPreference(Constant.DEFAULT_CITY,getString(R.string.default_city));
		if(default_city!=null&&default_city!=""){
			return default_city;
		}else{
			return null;
		}
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();		
		if(mLocationBroadcastReceiver!=null){
			this.unregisterReceiver(mLocationBroadcastReceiver);
		}
	}

	private void startLacation() {
		// 注册广播
		IntentFilter filter = new IntentFilter();
		filter.addAction(Constant.LOCATION_ACTION);
		mLocationBroadcastReceiver= new LocationBroadcastReceiver();
		this.registerReceiver(mLocationBroadcastReceiver, filter);

		// 启动服务
		Intent intent = new Intent();
		intent.setClass(this, LocationService.class);
		startService(intent);
		
		// 启动weather 服务
		Intent weather_intent = new Intent();
		weather_intent.setClass(this, NetWeatherService.class);
		startService(weather_intent);
	}

	@Override
	public void onProtolResultSuccess() {
		// TODO Auto-generated method stub
		initDao();
	}

	@Override
	public void onProtolResultFails() {
		// TODO Auto-generated method stub
		makeAlertDialog("无网络连接", "无网络连接，点击确定退出", false, true);
	} 


	void initDao(){
		LogUtil.d( "main menu initDao");
		mReverseGeocodeDao = new ReverseGeocodeDao(this, this);
		mNewsListDao = new NewsListDao(this, this);
		mWeatherServiceDao = new WeatherServiceDao(this, this);
		mLimitNumDao = new LimitNumDao(this, this);

		testLimitAndWeather();
		//checkAllCity();
		//checkHotCity();
		// 获取新闻数据
	}

	/**
	 * 初始化控件、数据
	 */
	private void initView() {
		rlQueryViolation = (RelativeLayout) findViewById(R.id.rl_query_violation);
		rlTodayLimit = (RelativeLayout) findViewById(R.id.rl_today_limit);
		rlNews = (RelativeLayout) findViewById(R.id.rl_news);
		llWeather = (ViewGroup) findViewById(R.id.rl_weather);
		lv = (ListView) findViewById(R.id.lv_weather_list);
		ivBack = (ImageView) findViewById(R.id.iv_back);
		ivWeatherShow = (ImageView) findViewById(R.id.iv_weather_show);
		
		forecastConditions = new ArrayList<ForecastConditionsBean>();
		adapter = new WeatherListAdapter(this, forecastConditions);
		lv.setAdapter(adapter);
		PreferenceUtils.savePreference(Constant.DEFAULT_CITY, "深圳市");
		tvPosition = (TextView) findViewById(R.id.tv_position_city);
		tv_mweek = (TextView) findViewById(R.id.tv_mweek);
		tv_temperature = (TextView) findViewById(R.id.tv_temperature);
		tv_state = (TextView) findViewById(R.id.tv_state);
		tv_prompt = (TextView) findViewById(R.id.tv_prompt);
		tvToday = (TextView) findViewById(R.id.tv_today);

		
       // weather
		ivBack.setOnClickListener(this);
		rlQueryViolation.setOnClickListener(this);
		rlTodayLimit.setOnClickListener(this);
		rlNews.setOnClickListener(this);
		llWeather.setOnClickListener(this);
		// limit
		tv_limit_number = (TextView) findViewById(R.id.tv_limit_number);
		tv_limit_position = (TextView) findViewById(R.id.tv_limit_position);

		lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				intentWeatherMessage();
			}
		});
		
	}

	/**
	 * 进入天气界面
	 */
	private void intentWeatherMessage() {

		Bundle bundle = new Bundle();
		bundle.putString("CITY_NAME", mDefaultCity);
		ActivityUtil.intentActivity(MainActivity.this, WeatherSinglePageActivity.class, bundle);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.iv_back:
			finish();
			break;
		case R.id.rl_today_limit:
			ActivityUtil.intentActivity(MainActivity.this, LimitNumActivity.class, null);
			break;
		case R.id.rl_query_violation:
			ActivityUtil.intentActivity(MainActivity.this, QueryViolationActivity.class, null);
			break;
		case R.id.rl_news:
			ActivityUtil.intentActivity(MainActivity.this, NewsMainActivity.class, null);
			break;
		case R.id.rl_weather:
			intentWeatherMessage();
			//ActivityUtil.intentActivity(MainActivity.this, NewsMainActivity.class, null);
			break;
		}
	}
	LocationBroadcastReceiver mLocationBroadcastReceiver;
	private TextView tv_mweek;
	private TextView tv_temperature;
	private TextView tv_state;
	private TextView tv_prompt;
	private TextView tv_limit_position;
	
	private class LocationBroadcastReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {			
			
			if (!intent.getAction().equals(Constant.LOCATION_ACTION)) return;
			String latitude = intent.getStringExtra(Constant.LOCATION_LATITUDE);
			String longitude = intent.getStringExtra(Constant.LOCATION_LONGITUDE);
			LogUtil.e("latitude = "+latitude);
			LogUtil.e("longitude = "+longitude);
			// 根据经纬度获取城市名称
			if(mReverseGeocodeDao!=null){
				mReverseGeocodeDao.getReverseGeocode(latitude, longitude);
			}
//			MainActivity.this.unregisterReceiver(this);// 不需要时注销
		}
	}		
	public void checkAllCity(){
		if(needToUpdateAllCity()){
			LogUtil.d( "need update all city");
			requestAllCity();
		}else{
			LogUtil.d( "not need update all city");
		}
	}
	
	void requestAllCity(){
		mGetAllCityDao = new GetAllCityDao(this, this);
		mGetAllCityDao.getAllList();
	}
    public boolean needToUpdateAllCity(){
    	String all_city_latest = PreferenceUtils.getPreference("all_city_latest");
    	
    	if(all_city_latest!=null&&all_city_latest!=""){

        	String current = TimeTool.getCurrentDates();
        	if(all_city_latest.equals(current)){
        		return false;
        	}else{
        		return true; 
        	}

    	}else{
    		return true;
    	}
    }
    
    
	public void checkHotCity(){
		if(needToUpdateHotCity()){
			LogUtil.d( "need update hot city");
			requestHotCity();
		}else{
			LogUtil.d( "not need update all city");
		}
	}
	
	void requestHotCity(){
		mGetHotCityDao = new GetHotCityDao(this, this);
		mGetHotCityDao.getHotList();
	}
    public boolean needToUpdateHotCity(){
    	String hot_city_latest = PreferenceUtils.getPreference("hot_city_latest");
    	
    	if(hot_city_latest!=null&&hot_city_latest!=""){

        	String current = TimeTool.getCurrentDates();
        	if(hot_city_latest.equals(current)){
        		return false;
        	}else{
        		return true; 
        	}

    	}else{
    		return true;
    	}
    }
	
}
